package com.aixingfu.sports.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.aixingfu.sports.MVP.contract.SignUploadContract;
import com.aixingfu.sports.MVP.presenter.SignUploadPresenter;
import com.aixingfu.sports.Model.SignUploadModel;
import com.aixingfu.sports.R;
import com.aixingfu.sports.bean.AutographPage;
import com.aixingfu.sports.view.SignatureView;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.orie.librarybase.base.BaseActivity;
import com.vondear.rxtool.view.RxToast;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//续费签名页
@Route(path = "/main/AutographPageRenewActivity")
public class AutographPageRenewActivity extends BaseActivity implements SignUploadContract.MyView {

    @BindView(R.id.signature_pad)
    SignatureView mSignaturePad;
    @BindView(R.id.btn_out)
    Button btnOut;
    @BindView(R.id.clear_button)
    Button mClearButton;
    @BindView(R.id.save_button)
    Button mSaveButton;
    @BindView(R.id.buttons_container)
    LinearLayout buttonsContainer;
    private SignUploadPresenter signUploadPresenter;
    private String type;
    @Override
    protected int provideContentViewId() {
        return R.layout.activity_autograph_page_renew;
    }

    public static void startActivityByRoute() {
        ARouter.getInstance().build("/main/AutographPageRenewActivity").navigation();
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        ButterKnife.bind(this);
        Bundle bundle = getIntent().getExtras();
        type = bundle.getString("type", "");
        signUploadPresenter = new SignUploadPresenter();
        signUploadPresenter.attachView(this);
        setpermissions();
        mSignaturePad.setOnSignedListener(new SignatureView.OnSignedListener() {
            @Override
            public void onSigned() {
                btnOut.setEnabled(true);
                mSaveButton.setEnabled(true);
                mClearButton.setEnabled(true);
            }

            @Override
            public void onClear() {
                btnOut.setEnabled(true);
                mSaveButton.setEnabled(false);
                mClearButton.setEnabled(false);
            }
        });
    }
    public void setpermissions() {
        if (Build.VERSION.SDK_INT >= 23) {
            int REQUEST_CODE_CONTACT = 101;
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            //验证是否许可权限
            for (String str : permissions) {
                if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                }
            }
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
    @Override
    protected void initEvent() {

    }

    @Override
    protected void beforeInit() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_out, R.id.clear_button, R.id.save_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_out:
                finish();
                break;
            case R.id.clear_button:
                mSignaturePad.clear();
                break;
            case R.id.save_button:
                Bitmap signatureBitmap = mSignaturePad.getSignatureBitmap();
                File file = compressImage(signatureBitmap);
                getUserSign(file);
                break;
        }
    }
    /**
     * 压缩图片（质量压缩）
     *
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }
    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }
    public void getUserSign(File file) {
        if (signUploadPresenter.isViewAttached()) {
            HashMap<String, String> map = new HashMap<>();
            map.put("type", type);
            signUploadPresenter.getSignUpload(file, map);
        }
    }
    @Override
    public void showToast(String msg, String state) {

    }

    @Override
    public void setSignUpload(SignUploadModel data) {
        if (data.getCode() == 1) {
            RxToast.normal(AutographPageRenewActivity.this, data.getMessage()).show();
            if ("1".equals(type)) {
                // 发布事件
                EventBus.getDefault().post(new AutographPage(type, data.getData().getMember_sign()));
            } else if ("2".equals(type)) {
                // 发布事件
                EventBus.getDefault().post(new AutographPage(type, data.getData().getHuiji_sign()));
            }
            finish();
        } else {
            RxToast.normal(AutographPageRenewActivity.this, data.getMessage()).show();
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void hideLoading() {
dismissLoadingDialog();
    }

    @Override
    public Context getMyContext() {
        return this;
    }
}
